package cn.xunjie.ymcc.service.impl;

import cn.xunjie.ymcc.domain.KillActivity;
import cn.xunjie.ymcc.domain.KillCourse;
import cn.xunjie.ymcc.mapper.KillActivityMapper;
import cn.xunjie.ymcc.service.IKillActivityService;
import cn.xunjie.ymcc.service.IKillCourseService;
import cn.xunjie.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue.jiao
 * @since 2022-08-04
 */
@Service
@Slf4j
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {
    @Autowired
    private IKillCourseService killCourseService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void publish(Long acitityId) {
        Wrapper<KillCourse> query = new EntityWrapper<>();
        query.eq("activity_id",acitityId);
        List<KillCourse> killCourses = killCourseService.selectList(query);
        KillCourse killCourse = killCourses.get(0);
        Date startTime = killCourse.getStartTime();
        boolean before = new Date().before(startTime);
        AssertUtil.isTrue(before,"活动时间不合法，发布失败");
        killCourses.forEach(course->{
            String key = acitityId+":"+course.getId();
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            boolean setPermits = semaphore.trySetPermits(course.getKillCount());
            if(setPermits){
                log.info("添加成功{}",course);
                redisTemplate.opsForHash().put(acitityId.toString(),course.getId().toString(),course);
            }else{
                log.info("添加秒杀课程失败{}",course);
            }

        });

    }
}
